<template>
  <a-flex vertical style="height: 100vh; padding: 16px;">
    <a-flex gap="small" style="margin-bottom: 16px">
      <a-select
        v-model:value="selectedDatasource"
        style="width: 200px"
        placeholder="请选择数据源"
        @change="handleDatasourceChange"
      >
        <a-select-option v-for="ds in datasources" :key="ds.id" :value="ds.id">
          {{ ds.name }}
        </a-select-option>
      </a-select>
      <a-button @click="clearMessages">清空聊天</a-button>
    </a-flex>
    <div style="flex: 1; min-height: 0; position: relative;">
      <Bubble.List
        ref="listRef"
        :roles="roles"
        :style="{ height: '100%', overflowY: 'auto' }"
        :items="messages.map(({ id, message, status, thoughts }) => ({
          key: id,
          role: status === 'local' ? 'local' : 'ai',
          content: message,
          header: thoughts ? h(ThoughtChain, {
            items: thoughts,
            collapsible: true,
            style: { marginBottom: '12px' }
          }) : undefined
        }))"
      />
    </div>
    <div style="margin-top: 16px;">
      <Sender
        :loading="senderLoading"
        :value="content"
        @change="setContent"
        @submit="handleSubmit"
      />
    </div>
  </a-flex>
</template>

<script setup>
import { ref, h, onMounted, nextTick } from 'vue'
import { UserOutlined, CheckCircleOutlined, InfoCircleOutlined, LoadingOutlined, LikeOutlined, DislikeOutlined } from '@ant-design/icons-vue'
import { Bubble, Sender, ThoughtChain } from 'ant-design-x-vue'
import {App, Table, Typography} from 'ant-design-vue'
import tool from '@/utils/tool'
import aiChatApi from '@/api/ai/aiChatApi'
import aiDatasourceConfigApi from '@/api/ai/aiDatasourceConfigApi'

defineOptions({
  name: 'SqlChat'
})

import { message } from 'ant-design-vue'
import trainDataApi from "@/api/ai/trainDataApi";
const renderTable = (content) => {
  if (!content) return content

  // 处理SqlExecuteResponse返回的数据结构
  let columns = []
  let dataArray = []

  if (content.columns && content.records) {
    // 处理列定义
    columns = content.columns.map(columnName => ({
      title: columnName,
      dataIndex: columnName,
      key: columnName,
      align: 'center',
      ellipsis: true
    }))
    // 处理数据记录
    dataArray = content.records
  } else {
    // 兼容其他数据结构
    dataArray = Array.isArray(content) ? content : [content]
    if (dataArray.length === 0 || typeof dataArray[0] !== 'object') return content

    columns = Object.keys(dataArray[0]).map(key => ({
      title: key,
      dataIndex: key,
      key: key,
      align: 'center',
      ellipsis: true
    }))
  }

  return h(Typography, null, {
    default: () => h('div', { style: { margin: '12px 0' } }, [
      h(Table, {
        columns: columns,
        dataSource: dataArray,
        size: 'middle',
        bordered: true,
        pagination: {
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true
        },
        scroll: { x: true },
        style: {
          backgroundColor: '#fff',
          borderRadius: '8px',
          boxShadow: '0 2px 8px rgba(0,0,0,0.15)'
        }
      }),
      h('div', {
        style: {
          display: 'flex',
          justifyContent: 'flex-end',
          gap: '12px',
          marginTop: '12px'
        }
      }, [
        h('div', {
          style: {
            cursor: 'pointer',
            display: 'flex',
            alignItems: 'center',
            gap: '4px'
          },
          onClick: async () => {
            const currentAiMessage = messages.value[messages.value.length - 1]
            const userMessage = messages.value[messages.value.length - 2]
            try {
              await trainDataApi.trainDataSubmitForm({
                question: userMessage.message,
				  sqlText: JSON.parse(currentAiMessage.thoughts[1].content).sql,
				  dataType: 'sql',
				  isPositiveExample: 1
              })
              message.success('感谢您的反馈!')
            } catch (error) {
              message.error('提交反馈失败：' + error.message)
            }
          }
        }, [
          h(LikeOutlined),
          '有帮助'
        ]),
        h('div', {
          style: {
            cursor: 'pointer',
            display: 'flex',
            alignItems: 'center',
            gap: '4px'
          },
          onClick: async () => {
            const currentAiMessage = messages.value[messages.value.length - 1]
            const userMessage = messages.value[messages.value.length - 2]
            try {
              await trainDataApi.trainDataSubmitForm({
                question: userMessage.message,
				  sqlText: JSON.parse(currentAiMessage.thoughts[1].content).sql,
				  dataType: 'sql',
				  isPositiveExample: 0
              })
              message.success('感谢您的反馈!')
            } catch (error) {
              message.error('提交反馈失败：' + error.message)
            }
          }
        }, [
          h(DislikeOutlined),
          '没帮助'
        ])
      ])
    ])
  })
}
const roles = {
  ai: {
    placement: 'start',
    avatar: { icon: h(UserOutlined), style: { background: '#fde3cf' } },
    style: {
      maxWidth: '100%',
    },
	  messageRender: renderTable

  },
  local: {
    placement: 'end',
    avatar: { icon: h(UserOutlined), style: { background: '#87d068' } },
  },
}

const content = ref('')
const senderLoading = ref(false)
const messages = ref([])
const listRef = ref(null)
const datasources = ref([])
const selectedDatasource = ref(null)

const getStatusIcon = (status) => {
  switch (status) {
    case 'success':
      return h(CheckCircleOutlined)
    case 'error':
      return h(InfoCircleOutlined)
    case 'pending':
      return h(LoadingOutlined)
    default:
      return undefined
  }
}

const setContent = (v) => {
  content.value = v
}

const handleDatasourceChange = (value) => {
  selectedDatasource.value = value
}

const clearMessages = () => {
  messages.value = []
}

const loadDatasources = async () => {
  try {
    const result = await aiDatasourceConfigApi.aiDatasourceConfigPage({
      page: 1,
      limit: 100
    })
    datasources.value = result.records || []
    if (datasources.value.length > 0) {
      selectedDatasource.value = datasources.value[0].id
    }
  } catch (error) {
    message.error('加载数据源失败：' + error.message)
  }
}

const handleSubmit = async () => {
  if (!content.value.trim()) return
  if (!selectedDatasource.value) {
    message.warning('请先选择数据源')
    return
  }
  senderLoading.value = true

  const userMessage = {
    id: Date.now(),
    message: content.value,
    status: 'local'
  }

  // 创建新的AI消息对象
  const newAiMessage = {
    id: Date.now() + 1,
    message: '',
    status: 'ai',
    thoughts: []
  }

  // 更新消息列表
  messages.value = [...messages.value, userMessage, newAiMessage]
  content.value = ''
  senderLoading.value = true
  nextTick(() => {
    if (listRef.value && listRef.value.$el) {
      listRef.value.$el.scrollTop = listRef.value.$el.scrollHeight
    }
  })
  nextTick(() => {
    if (listRef.value && listRef.value.$el) {
      listRef.value.$el.scrollTop = listRef.value.$el.scrollHeight
    }
  })

  try {
    // 获取当前AI消息对象
    const currentAiMessage = messages.value[messages.value.length - 1]

    // 向量检索
    currentAiMessage.thoughts.push({
      title: '向量检索相似内容',
      status: 'pending',
      icon: getStatusIcon('pending'),
      description: '正在检索相似内容...'
    })
    messages.value = [...messages.value]
    nextTick(() => {
      if (listRef.value && listRef.value.$el) {
        listRef.value.$el.scrollTop = listRef.value.$el.scrollHeight
      }
    })

    try {
      const vectorResult = await aiChatApi.vectorSearch(userMessage.message)
      currentAiMessage.thoughts[0].status = 'success'
      currentAiMessage.thoughts[0].icon = getStatusIcon('success')
      currentAiMessage.thoughts[0].description = '检索完成'
      currentAiMessage.thoughts[0].content = JSON.stringify(vectorResult, null, 2)
      messages.value = [...messages.value]
      nextTick(() => {
        if (listRef.value && listRef.value.$el) {
          listRef.value.$el.scrollTop = listRef.value.$el.scrollHeight
        }
      })

      // SQL生成
      currentAiMessage.thoughts.push({
        title: 'SQL生成',
        status: 'pending',
        icon: getStatusIcon('pending'),
        description: '正在生成SQL...',
      })
      messages.value = [...messages.value]
      listRef.value.$el.scrollTop = listRef.value.$el.scrollHeight

      const sqlResult = await aiChatApi.generateSQL({
        query: userMessage.message,
        context: vectorResult,
        datasourceId: selectedDatasource.value
      })

      currentAiMessage.thoughts[1].status = 'success'
      currentAiMessage.thoughts[1].icon = getStatusIcon('success')
      currentAiMessage.thoughts[1].description = '生成完成'
      currentAiMessage.thoughts[1].content = JSON.stringify(sqlResult, null, 2)
      messages.value = [...messages.value]
      nextTick(() => {
        if (listRef.value && listRef.value.$el) {
          listRef.value.$el.scrollTop = listRef.value.$el.scrollHeight
        }
      })

      // 执行SQL
      currentAiMessage.thoughts.push({
        title: 'SQL执行',
        status: 'pending',
        icon: getStatusIcon('pending'),
        description: '正在执行SQL...',
      })
      messages.value = [...messages.value]
      listRef.value.$el.scrollTop = listRef.value.$el.scrollHeight

      const executionResult = await aiChatApi.executeSQL({
        sql: sqlResult.sql,
        datasourceId: selectedDatasource.value
      })

      currentAiMessage.thoughts[2].status = 'success'
      currentAiMessage.thoughts[2].icon = getStatusIcon('success')
      currentAiMessage.thoughts[2].description = '执行完成'
      currentAiMessage.thoughts[2].content = JSON.stringify(executionResult, null, 2)
      currentAiMessage.message = executionResult
      messages.value = [...messages.value]
      nextTick(() => {
        if (listRef.value && listRef.value.$el) {
          listRef.value.$el.scrollTop = listRef.value.$el.scrollHeight
        }
      })

    } catch (error) {
      // 获取错误信息
      const errorMsg = error.response?.data?.msg || error.message || '未知错误'

      // 更新最后一个思维链的状态
      const lastThought = currentAiMessage.thoughts[currentAiMessage.thoughts.length - 1]
      if (lastThought) {
        lastThought.status = 'error'
        lastThought.icon = getStatusIcon('error')
        lastThought.description = errorMsg
        lastThought.content = JSON.stringify({
          error: errorMsg,
          details: error.response?.data || error
        }, null, 2)
      }

      // 更新消息列表
      messages.value = [...messages.value]
      nextTick(() => {
        if (listRef.value && listRef.value.$el) {
          listRef.value.$el.scrollTop = listRef.value.$el.scrollHeight
        }
      })
      throw error
    }
  } finally {
    senderLoading.value = false
  }
}

onMounted(() => {
  loadDatasources()
})
</script>
